package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.CoordinaModel;
import models.OrderModel;
import models.OrderProductModel;
import models.RouteModel;
import models.StaffModel;
import models.StoreItemModel;
import models.TransactionModel;
import admin.data.CoordinaData;
import admin.data.RouteData;
import admin.data.StaffData;
import admin.data.StoreItemData;
import admin.data.TransactionData;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import data.OrderData;


@SuppressWarnings("serial")
public class StoreImportServlet extends HttpServlet {
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setCharacterEncoding("UTF-8");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String params = path.replaceAll("/admin/store-item/import/", "");	
		ArrayList<CoordinaModel> listCoordina = new ArrayList<CoordinaModel>();	
		if(params.length()>8)
		{
			CoordinaData coordinaData = new CoordinaData();
			CoordinaModel coordinaModel = coordinaData.getById(params);	
			if((coordinaModel==null)||(coordinaModel.getStatus()!=3))
			{
				HttpSession session = request.getSession();
				session.setAttribute("alert", "Mã tuyến sai hoặc tuyến đã được xác nhận trả hàng !");
				
				response.sendRedirect("/admin/store-item/import/");
			}
			else
			{
				StaffData staffData = new StaffData();
				StaffModel staff = staffData.getByCode(coordinaModel.getEmployeeId());
				String[] listOrderId = coordinaModel.getListOrder().split(",");
				TreeMap<String, OrderProductModel> mapOrderProduct = new TreeMap<String, OrderProductModel>();
				TreeMap<String, Integer> mapProductReturn = new TreeMap<String, Integer>();
				int totalVC = 0; 
				int totalSP = 0; 
				for (int i = 0; i < listOrderId.length; i++) {
					if(listOrderId[i].length()>9)
					{
						OrderModel orderModel = OrderData.getOrder(listOrderId[i]);
						TreeMap<String, Integer> productReturn = OrderData.getProductReturn(orderModel.getReturnCoordina());
						List<String> listOrderProduct = orderModel.getListOrderProduct();
						for (String stringOrderProduct : listOrderProduct) {
							OrderProductModel orderProduct = new OrderProductModel();
							orderProduct.getValueFromString(stringOrderProduct);	
							if (mapOrderProduct.containsKey(orderProduct.getProductId())) {
								int quantity = mapOrderProduct.get(orderProduct.getProductId()).getQuantity()+orderProduct.getQuantity();
								orderProduct.setStoreType(orderModel.getDealProductType());
								orderProduct.setQuantity(quantity);
							} else {
								orderProduct.setStoreType(orderModel.getDealProductType());
								if(orderModel.getDealProductType()==0) {totalVC++;}
								if(orderModel.getDealProductType()==1) {totalSP++;}
							}
							mapOrderProduct.put(orderProduct.getProductId(), orderProduct);
						}
						
						for (Map.Entry<String, Integer> entry : productReturn.entrySet()) {
							if (mapProductReturn.containsKey(entry.getKey())) {
								mapProductReturn.put(entry.getKey(), entry.getValue()+mapProductReturn.get(entry.getKey()));
							} else {
								mapProductReturn.put(entry.getKey(), entry.getValue());
							}
						}
					}
				}
				
				for (Map.Entry<String, Integer> entry : mapProductReturn.entrySet()) {
					if (mapOrderProduct.containsKey(entry.getKey())) {
						int productDelivered = mapOrderProduct.get(entry.getKey()).getQuantity() - mapProductReturn.get(entry.getKey());
						mapOrderProduct.get(entry.getKey()).setProductReturn(mapProductReturn.get(entry.getKey()));
						mapOrderProduct.get(entry.getKey()).setProductDelivered(productDelivered);
					}
				}
				
				try {
					Cache cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
					cache.put("mapOrderProduct/"+coordinaModel.getId(), mapOrderProduct);
				} catch (CacheException e) {
					
				}
				
				request.setAttribute("coordinaModel", coordinaModel);
				request.setAttribute("staff", staff);
				request.setAttribute("mapOrderProduct", mapOrderProduct);
				request.setAttribute("mapProductReturn", mapProductReturn);
				request.setAttribute("totalVC", totalVC);
				request.setAttribute("totalSP", totalSP);
				try {
					request.getRequestDispatcher("/admin/pages/store_import.jsp").forward(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		else
		{
			CoordinaData coordinaData = new CoordinaData();
			listCoordina = coordinaData.getCoordina("","3","","","","");
			RouteData routeData = new RouteData();
			TreeMap<String, RouteModel> mapRoute = routeData.getMapRoute();
			request.setAttribute("mapRoute", mapRoute);
			request.setAttribute("listCoordina", listCoordina);
			try {
				request.getRequestDispatcher("/admin/pages/store_import_list.jsp").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
	}
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String action = (String) request.getParameter("action");
		String coordinaId = (String) request.getParameter("coordinaId");
		
		if (action.equalsIgnoreCase("search"))
		{
			response.sendRedirect("/admin/store-item/import/"+coordinaId);
		}
		
		if (action.equalsIgnoreCase("saveImport")) {
			TreeMap<String, OrderProductModel> mapOrderProduct = null;
			try {
				Cache cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
				mapOrderProduct = (TreeMap<String, OrderProductModel>) cache.get("mapOrderProduct/"+coordinaId);
			} catch (CacheException e) {
				mapOrderProduct = null;
			}
			if(mapOrderProduct!=null)
			{
				CoordinaData coordinaData = new CoordinaData();
				CoordinaModel coordinaModel = coordinaData.getById(coordinaId);;
				coordinaModel.setStatus(4);
				coordinaModel.setCreated(new Date());
				coordinaData.insert(coordinaModel);	
				
				Objectify objfy = ObjectifyService.beginTransaction();			
				for (Map.Entry<String, OrderProductModel> entry : mapOrderProduct.entrySet()) {
					StoreItemData storeItemData = new StoreItemData();
					StoreItemModel storeItemModel = storeItemData.getItem(entry.getKey());
					int inventory = storeItemModel.getInventory() + entry.getValue().getProductReturn();
					storeItemModel.setInventory(inventory);
					int delivery = storeItemModel.getDelivery() - entry.getValue().getQuantity();
					storeItemModel.setDelivery(delivery);
					int delivered = storeItemModel.getDelivered() + entry.getValue().getProductDelivered();
					storeItemModel.setDelivered(delivered);
					int loc = entry.getValue().getProductReturn();
					storeItemModel.setLoc(loc);
					storeItemData.insert(storeItemModel,objfy);
					
					TransactionModel transaction = new TransactionModel();
					transaction.setTransactionId(IdUniqueHelper.getId());
					transaction.setDealId(storeItemModel.getDealId());
					transaction.setStoreItemId(storeItemModel.getId());
					transaction.setInventory(storeItemModel.getInventory());
					transaction.setDelivered(storeItemModel.getDelivered());
					transaction.setDelivery(storeItemModel.getDelivery());
					transaction.setLoc(storeItemModel.getLoc());
					transaction.setType(1);
					transaction.setDate(Calendar.getInstance().getTime());
					transaction.setAmount(entry.getValue().getProductReturn());
					TransactionData transactionData = new TransactionData();
					transactionData.insert(transaction);
				}
				objfy.getTxn().commit();		
	
				HttpSession session = request.getSession();
				session.setAttribute("success", "Nhập trả hàng theo LOC thành công !");				
				response.sendRedirect("/admin/store-item/import/");
			}
			else
			{
				HttpSession session = request.getSession();
				session.setAttribute("alert", "Nhập hàng theo LOC không thành công !");				
				response.sendRedirect("/admin/store-item/import/"+coordinaId);
			}
		} 	
	}
}